# -*- coding: utf-8 -*-
import logging

from celery.result import AsyncResult
from django.http import JsonResponse, HttpResponse
from django.test import Client
from rest_framework.decorators import action
from rest_framework.viewsets import GenericViewSet

from django_service.messages import default_response, message_response
from django_package.application.tasks import async_task

logger = logging.getLogger(__name__)


class AsyncTaskView(GenericViewSet):
    """
    
    1.解决获取多实体的日期区间数据接口性能问题
        每一个接口都要有实体代码data_code，起始日期start_date，截止日期end_date，但参数可能在url和body里
    
    """

    @action(methods=['post'], detail=False)
    def request_forward(self, *args, **kwargs):
        logger.info(self.request.data)

        query_params = self.request.query_params
        headers = self.request.headers
        data = self.request.data
        user_id = self.request.user.id
        real_path = data.get('real_path')

        # factory = RequestFactory()
        # request = factory.post(
        #     path='post_sync',
        #     HTTP_X_CSRFTOKEN=self.request.META.get('HTTP_X_CSRFTOKEN'),
        # )
        # request.query_params = query_params
        # request.data = data
        # request.user = get_user_model().objects.get(pk=user_id)
        # handle = SyncView.as_view({'post': 'post_sync'})
        # response = handle(request)

        client = Client()
        client.force_login(self.request.user)
        response = client.post(
            real_path,
            data,
        )

        logger.info(f'response:{response.content.decode(encoding=response.charset)}')
        return HttpResponse(response.content)
        # return JsonResponse(response.content.decode(encoding=response.charset))

    @action(methods=['post'], detail=False)
    def delay_async_task(self, *args, **kwargs):
        query_params = self.request.query_params
        data = self.request.data
        user_id = self.request.user.id
        real_path = data.get('real_path')
        async_result: AsyncResult = async_task.delay(query_params, data, user_id, real_path)
        return JsonResponse(message_response(async_result.task_id))

    @action(methods=['post'], detail=False)
    def check_task_ready(self, *args, **kwargs):
        task_id = self.request.query_params.get('task_id')
        async_result = AsyncResult(task_id)
        if async_result.ready():
            result = {'status': 'completed', 'result': async_result.result}
        else:
            result = {'status': 'executing'}
        return JsonResponse(message_response(result))

    @action(methods=['get'], detail=False)
    def get_async_result(self, *args, **kwargs):
        task_id = self.request.query_params['task_id']
        logger.info(f'task_id:{task_id}')
        return JsonResponse(default_response())
